// pages/add/add.js
import {
  serviceFacilities,
  touristAddInfo,
  campAddCampsite,
} from "../../api/camp"
import {
  base_url
} from "../../utils/request"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    base_url: base_url,
    type: '1', //步骤判断展示数据
    currentVal: 0, //步骤累加值
    showCondition: false,
    campBusinessHours: true, //营地时间状态
    campTypeHide: true, //营地类型选择状态

    campLocation: "", //营地位置
    latitude: 0, //维度
    longitude: 0, //经度
    userType: null, //1运营者0游客
    businessHours: null, //营地时间数据
    campType: null, //营地类型数据
    campImgs: [], //商家信息图片
    // 存草稿
    modalHide: true,
    // 服务设施列表
    facilitiesList: [],
    // 服务设施选中数据
    facilitiesCurrentData: {},
    preFacilitiesArr: null, //服务预览数据
    markers: [],
    campCondotionStatus: false, //添加营位开关
    campConditionDatas: [], //营位数据列表
    addConditionStatus: true, //添加营位类型开关
    tourisCampImgs: [], //游客图片
    touristConditionData: [], //游客营位

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //获取服务设施
    this.getFacilitiesList()
    this.setData({
      userType: options.type
    })
  },
  // 展示时间
  showCampTime() {
    this.setData({
      campBusinessHours: false
    })
  },
  //获取选中时间
  getCampBusinessTime(e) {
    this.setData({
      businessHours: e.detail.businessHours
    })
  },
  // 展示营地类型
  searchbarClick() {
    this.setData({
      campTypeHide: false,
    })
  },
  //获取营地类型数据
  getCampType(e) {
    this.setData({
      campType: e.detail
    })
  },
  //获取图片
  getUploadList(l) {
    this.setData({
      campImgs: l.detail,
      tourisCampImgs: l.detail
    })
  },
  //删除商家图片
  delImgs(u) {
    this.data.campImgs.splice(u.currentTarget.dataset.index, 1)
    this.setData({
      campImgs: this.data.campImgs
    })
  },


  //获取服务设施
  async getFacilitiesList() {
    const result = await serviceFacilities()
    const dl = result.data.map(item => {
      item.facilities.map(f => f.state = 0)
      return item;
    })
    this.setData({
      facilitiesList: dl
    })
    console.log(result)
  },
  //服务设施,获取提交数据
  changeFacilitiesArr(e) {
    let facilityId = e.currentTarget.dataset.facilityid;
    let currentArr = [],
      preFacilitiesArr = [];
    const result = this.data.facilitiesList.map(item => {
      for (let f of item.facilities) { //实现提交数据
        if (f.facilityId === facilityId) f.state == 1 ? (f.state = 0) : (f.state = 1);
        if (f.state == 1) currentArr.push(f.facilityId);
      }
      return item;
    })
    result.map(item => {
      item.facilities.filter(f => {
        if (f.state == 1) {
          if (item.ftId == f.ftId) {
            preFacilitiesArr.push({
              ftId: item.ftId,
              ftName: item.ftName,
              fObj: f
            })
          }

        }
      })
    })
    // console.log(preFacilitiesArr)
    this.setData({
      facilitiesList: result,
      facilitiesCurrentData: currentArr,
      preFacilitiesArr: preFacilitiesArr
    })
  },

  // 滑动监听
  swiperChang: function (e) {
    this.setData({
      currentVal: e.detail.current
    });
  },
  // 禁止用户滑动
  catchTouchMove() {
    return false;
  },
  // 上一步
  toBack() {
    this.setData({
      currentVal: this.data.currentVal - 1
    })
  },
  // 下一步
  async toNext(e) {
    console.log(e)
    const formData = e.detail.value
    for (let key in formData) {
      if (formData[key] == "") {
        switch (key) {
          case 'campName':
            this.showToast('请输入营地名称')
            return;
          case 'location':
            this.showToast('请输入营地位置')
            return;
          case 'address':
            this.showToast('请输入具体地址')
            return;
          case 'timeType':
            this.showToast('请输入营业时间')
            return;
          case 'campType':
            this.showToast('请输入营地类型')
            return;
          case 'linkman':
            this.showToast('请输入联系人')
            return;
          case 'phone':
            this.showToast('请输入电话')
            return;
        }
      }
    }

    if (this.data.campImgs.length === 0 && this.data.currentVal == 0) {
      this.showToast("请选择图片")
      return;
    }

    if (this.data.facilitiesCurrentData === "" && this.data.currentVal == 1) {
      this.showToast("请选择服务设施")
      return;
    }
    if (this.data.currentVal == 2 && formData.introduce == "") {
      this.showToast("请填写营地介绍")
      return;
    }
    const instance = getApp()
    instance.globalData.campData['campInfo'] = {
      ...e.detail.value, //基础数据
      latitude: this.data.latitude, //维度
      longitude: this.data.longitude, //经度
      userType: this.data.userType, //1运营者0游客
      businessHours: this.data.businessHours, //营地时间数据
      campType: this.data.campType?.name, //营地类型数据id
      campTypeName: this.data.campType?.name, //营地类型名称
      campImgs: this.data.campImgs, //商家信息图片
      userId: wx.getStorageSync('userInfo').userId, //用户ID
    }
    instance.globalData.campData['facilitiesCurrentData'] = this.data.facilitiesCurrentData
    instance.globalData.campData['preFacilitiesArr'] = this.data.preFacilitiesArr
    console.log("营地信息数据--------------------------->", instance.globalData.campData);
    if (this.data.currentVal < 2) {
      this.setData({
        currentVal: this.data.currentVal + 1
      })
    }
    // 预览
    if (this.data.currentVal == 2 && formData.introduce != "") {
      wx.setStorageSync('preViewData', instance.globalData.campData)
      wx.navigateTo({
        url: `../preview/preview?type=${this.data.type}`,
      })
    }
  },
  //游客发布营地
  async touristSendData(e) {
    // console.log(e.detail.value, this.data.touristConditionData, this.data.tourisCampImgs)
    const formData = e.detail.value
    for (let key in formData) {
      if (formData[key] == "") {
        switch (key) {
          case 'campName':
            this.showToast('请输入营地名称')
            return;
          case 'location':
            this.showToast('请输入营地位置')
            return;
          case 'address':
            this.showToast('请输入具体地址')
            return;
          case 'campType':
            this.showToast('请输入营地类型')
            return;
          case 'linkman':
            this.showToast('请输入联系人')
            return;
          case 'phone':
            this.showToast('请输入电话')
            return;
        }
      }
    }

    if (this.data.tourisCampImgs.length === 0 ) {
      this.showToast("请选择图片")
      return;
    }
    if (e.detail.value.introduce == "") {
      this.showToast("请填写营地介绍")
      return;
    }
    let userId = wx.getStorageSync('userInfo').userId
    const campInfo = await touristAddInfo({
      "address": e.detail.value.address,
      "campName": e.detail.value.campName,
      "campType": e.detail.value.campType,
      "introduce":e.detail.value.introduce,
      "imageUrl": this.data.tourisCampImgs.join(","),
      "latitude": this.data.latitude,
      "longitude": this.data.longitude,
      "location": e.detail.value.location,
      "linkman": e.detail.value.linkman,
      "phone": e.detail.value.phone,
      "userId": userId,
      "userType": this.data.userType
    });
    if (campInfo.code == 200) {
      const factor = this.data.touristConditionData.map(item => {
        item.factor = item.factorId.join(",")
        item.campId = campInfo.msg
        return item
      })
      console.log(factor)
      const result = await campAddCampsite(factor)
      console.log(result)
      if (result.code == 200) {
        wx.hideLoading()
        wx.showModal({
          title: '系统提示',
          content: '上传成功',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              console.log(res.confirm,"--------->")
              wx.switchTab({
                url: '../index/index',
              })
            }
          }
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '上传失败',
          mask: true,
          duration: 2000
        })
      }
    }

  },
  showToast(title) {
    wx.showToast({
      title: title,
      icon: "error",
      mask: true,
      duration: 1500
    })
  },


  // 营地位置
  toCampLocation() {
    // wx.navigateTo({
    //   url: '/pages/campLocation/campLocation',
    // })
    // 检查用户权限状态
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          // 用户尚未授权或已拒绝授权
          // 主动请求授权
          this.requestLocationAuthorization();
        } else {
          // 已经授权，直接获取位置信息
          this.getUserLocation();
        }
      }
    });
  },
  requestLocationAuthorization() {
    // 请求用户授权位置信息
    wx.authorize({
      scope: 'scope.userLocation',
      success: () => {
        this.getUserLocation();
      },
      fail: (err) => {
        console.error('授权失败:', err);
        // 如果用户拒绝了授权，可以进一步提示用户去设置中手动开启
        this.showSettingPrompt();
      }
    });
  },

  showSettingPrompt() {
    // 提示用户去设置中开启位置权限
    wx.showModal({
      title: '需要位置权限',
      content: '请在设置中开启位置权限以正常使用本功能。',
      showCancel: false,
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          wx.openSetting({
            success: (settingRes) => {
              if (settingRes.authSetting['scope.userLocation']) {
                // 用户在设置中开启了位置权限
                this.getUserLocation();
              } else {
                // 用户仍然拒绝位置权限
                console.log('用户仍未开启位置权限');
              }
            },
          });
        }
      },
    });
  },
  getUserLocation() {
    wx.getLocation({
      // type: 'wgs84',
      type: 'gcj02',
      success: (res) => {
        // console.log(res, "返回的数据")
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        });
        wx.chooseLocation({
          longitude: this.data.longitude,
          latitude: this.data.latitude,
          success: (res) => {
            // console.log(res, '########');
            this.setData({
              latitude: res.latitude,
              longitude: res.longitude,
              campLocation: res.address
            });
          }
        })
      },
      fail: (err) => {
        console.error('获取位置失败:', err);
      },
      complete: () => {
        console.log('位置获取操作已完成');
      }
    });
  },
  // 营位类型
  toCampType() {
    this.setData({
      campCondotionStatus: true
    })
  },
  //营位选择数据
  campConditionList(e) {
    this.setData({
      campConditionDatas: e.detail,
      touristConditionData: e.detail
    })
  },
  //是否接待外来车位
  isConditionShow(e) {
    if (e.detail.value) {
      this.setData({
        addConditionStatus: false
      })
    } else {
      this.setData({
        addConditionStatus: true
      })
    }
  },
  // 开启模态框
  showModal() {
    this.setData({
      modalHide: false
    })
  },
  // 关闭模态框
  hideModal() {
    this.setData({
      modalHide: true
    })
  },




})